<template>
    <div class="page-wrapper">
        <div class="register-container">
            <!--注册卡片-->
            <div class="register-card">
                <div class="card-header">
                    <h1 class="title">创建账户</h1>
                    <p class="subtitle">加入我们，开启全新体验</p>
                </div>
                
                <van-form @submit="handleRegister" class="register-form">
                    <!-- 头像上传 -->
                    <div class="avatar-section">
                        <div class="avatar-upload">
                            <van-uploader v-model="avatarFile" :max-count="1" :after-read="afterRead"
                                :before-read="beforeRead" :disabled="uploading">
                                <div class="avatar-container" :class="{ 'uploading': uploading }">
                                    <div class="avatar-wrapper">
                                        <img v-if="avatarUrl && !uploading" :src="avatarUrl" class="avatar-image" alt="头像">
                                        <div v-else-if="uploading" class="avatar-uploading">
                                            <div class="spinner"></div>
                                            <span>上传中...</span>
                                        </div>
                                        <div v-else class="avatar-placeholder">
                                            <div class="icon-wrapper">
                                                <van-icon name="photograph" size="24" />
                                            </div>
                                            <span>上传头像</span>
                                        </div>
                                    </div>
                                    <div class="avatar-overlay">
                                        <van-icon name="plus" size="16" />
                                    </div>
                                </div>
                            </van-uploader>
                        </div>
                    </div>

                    <van-cell-group class="input-group">
                        <!-- 输入任意文本 -->
                        <van-field autocomplete="current-userAccount" v-model="registerForm.userAccount" type="text"
                            placeholder="请输入用户名" label="用户名" :rules="[
                                { required: true, message: '请输入用户名' },
                                { pattern: /^.{2,10}$/, message: '用户名在2到10字符之间' }
                            ]" />
                        <!-- 输入密码 -->
                        <van-field autocomplete="current-userPwd" v-model="registerForm.userPwd" type="password"
                            placeholder="请输入密码" label="密码" :rules="[
                                { required: true, message: '请填写密码' },
                                {
                                    pattern: /^[a-zA-Z0-9]{6,}$/,
                                    message: '密码至少要6位，只能包含字母和数字'
                                }
                            ]" />
                        <!-- 输入任意文本 -->
                        <van-field autocomplete="current-userName" v-model="registerForm.userName" type="text"
                            placeholder="请输入姓名" label="姓名" :rules="[
                                { required: true, message: '请输入姓名' },
                                { pattern: /^[\u4e00-\u9fa5]+$/, message: '请输入纯中文名称' }
                            ]" />
                        <!-- 输入手机号，调起手机号键盘 -->
                        <van-field autocomplete="current-userPhone" v-model="registerForm.userPhone" type="tel"
                            placeholder="请输入手机号" label="手机号" :rules="[
                                { required: true, message: '请输入手机号' },
                                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式（以13开头，11位数字）' }
                            ]" />
                    </van-cell-group>
                    
                    <div class="action-section">
                        <van-button round block type="primary" native-type="submit" :loading="loading" class="register-btn">
                            <span v-if="!loading">立即注册</span>
                            <span v-else>注册中...</span>
                        </van-button>
                        <div class="login-link">
                            已有账户？
                            <RouterLink to="/login" class="link">立即登录</RouterLink>
                        </div>
                    </div>
                </van-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { register, uploadImageApi } from '@/api';
import router from '@/router';
import { showToast } from 'vant';
import { ref } from 'vue';

// 注册表单数据
let registerForm = ref({
    userAccount: "",
    userPwd: "",
    userName: "",
    userPhone: "",
    userAvatar: ""
});

// 头像相关
const avatarFile = ref([]);
const avatarUrl = ref('');
const uploading = ref(false);
const loading = ref(false);

// 文件上传前的验证
const beforeRead = (file) => {
    console.log('文件信息:', {
        name: file.name,
        type: file.type,
        size: file.size
    });
    
    if (!file.type.startsWith('image/')) {
        showToast('请上传图片文件 (jpg, png, gif等)');
        return false;
    }
    if (file.size > 5 * 1024 * 1024) {
        showToast('图片大小不能超过5MB');
        return false;
    }
    return true;
};

// 文件读取后的处理 - 上传到服务器
const afterRead = async (file) => {
    uploading.value = true;
    
    try {
        const formData = new FormData();
        formData.append('image', file.file);
        
        console.log('开始上传文件:', file.file);
        showToast('正在上传头像...');
        
        const response = await uploadImageApi(formData);
        console.log('上传响应:', response);
        
        // 根据后端返回的数据结构调整
        const imageUrl = response.data?.url;
        
        if (!imageUrl) {
            throw new Error('服务器返回的图片URL为空');
        }
        
        // 构建完整的访问URL
        const baseUrl = window.location.origin;
        const fullImageUrl = baseUrl + imageUrl;
        
        console.log('完整图片URL:', fullImageUrl);
        
        avatarUrl.value = fullImageUrl;
        registerForm.value.userAvatar = fullImageUrl;
        
        showToast('头像上传成功');
    } catch (error) {
        console.error('头像上传失败详情:', {
            message: error.message,
            response: error.response?.data,
            status: error.response?.status
        });
        
        let errorMsg = '头像上传失败';
        if (error.response?.data?.message) {
            errorMsg += ': ' + error.response.data.message;
        } else if (error.message) {
            errorMsg += ': ' + error.message;
        }
        
        showToast(errorMsg);
        avatarFile.value = [];
    } finally {
        uploading.value = false;
    }
};

const handleRegister = async () => {
    if (uploading.value) {
        showToast('头像正在上传中，请稍后');
        return;
    }

    const fields = [
        { value: registerForm.value.userAccount, message: '请输入用户名' },
        { value: registerForm.value.userPwd, message: '请输入密码' },
        { value: registerForm.value.userName, message: '请输入姓名' },
        { value: registerForm.value.userPhone, message: '请输入手机号' }
    ];

    for (const field of fields) {
        if (!field.value) {
            showToast(field.message);
            return;
        }
    }

    loading.value = true;

    try {
        await register(registerForm.value);
        showToast('注册成功');
        router.push({ name: "login" })
    } catch (e) {
        showToast(e.message || '注册失败，请重试');
    } finally {
        loading.value = false;
    }
}
</script>

<style lang="scss" scoped>
.page-wrapper {
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    position: relative;
    
    &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"><polygon fill="rgba(255,255,255,0.05)" points="0,1000 1000,0 1000,1000"/></svg>');
        background-size: cover;
    }
}

.register-container {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    position: relative;
}

.register-card {
    width: 100%;
    max-width: 440px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 
        0 20px 60px rgba(0, 0, 0, 0.15),
        0 0 0 1px rgba(255, 255, 255, 0.1);
    transform: translateY(0);
    transition: all 0.3s ease;
    
    &:hover {
        transform: translateY(-5px);
        box-shadow: 
            0 25px 80px rgba(0, 0, 0, 0.2),
            0 0 0 1px rgba(255, 255, 255, 0.15);
    }
    
    .card-header {
        padding: 40px 40px 20px;
        text-align: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        position: relative;
        overflow: hidden;
        
        &::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
            background-size: 20px 20px;
            animation: float 6s ease-in-out infinite;
        }
        
        .title {
            font-size: 28px;
            font-weight: 700;
            margin: 0 0 8px 0;
            position: relative;
        }
        
        .subtitle {
            font-size: 14px;
            opacity: 0.9;
            margin: 0;
            font-weight: 400;
            position: relative;
        }
    }
}

.register-form {
    padding: 40px;
    
    .avatar-section {
        display: flex;
        justify-content: center;
        margin-bottom: 30px;
        
        .avatar-upload {
            :deep(.van-uploader__wrapper) {
                width: 120px;
                height: 120px;
            }
            
            :deep(.van-uploader__upload) {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
                border: none;
                background: transparent;
            }
            
            .avatar-container {
                width: 120px;
                height: 120px;
                border-radius: 50%;
                position: relative;
                cursor: pointer;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                
                &.uploading {
                    opacity: 0.7;
                }
                
                .avatar-wrapper {
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                    overflow: hidden;
                    border: 3px solid #e8e8e8;
                    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                    transition: all 0.3s ease;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    
                    .avatar-image {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }
                    
                    .avatar-placeholder,
                    .avatar-uploading {
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        color: #909399;
                        font-size: 12px;
                        
                        .icon-wrapper {
                            width: 48px;
                            height: 48px;
                            border-radius: 50%;
                            background: rgba(102, 126, 234, 0.1);
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            margin-bottom: 8px;
                            
                            .van-icon {
                                color: #667eea;
                            }
                        }
                    }
                    
                    .avatar-uploading {
                        color: #667eea;
                        
                        .spinner {
                            width: 24px;
                            height: 24px;
                            border: 2px solid #e8e8e8;
                            border-top: 2px solid #667eea;
                            border-radius: 50%;
                            animation: spin 1s linear infinite;
                            margin-bottom: 8px;
                        }
                    }
                }
                
                .avatar-overlay {
                    position: absolute;
                    bottom: 5px;
                    right: 5px;
                    width: 32px;
                    height: 32px;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: white;
                    border: 3px solid white;
                    opacity: 0;
                    transform: scale(0.8);
                    transition: all 0.3s ease;
                    
                    .van-icon {
                        font-size: 14px;
                    }
                }
                
                &:hover {
                    .avatar-wrapper {
                        border-color: #667eea;
                        transform: scale(1.05);
                    }
                    
                    .avatar-overlay {
                        opacity: 1;
                        transform: scale(1);
                    }
                }
            }
        }
    }
    
    .input-group {
        background: transparent;
        margin-bottom: 30px;
        
        :deep(.van-field) {
            padding: 16px 0;
            margin-bottom: 20px;
            background: transparent;
            border-bottom: 1px solid #e8e8e8;
            transition: all 0.3s ease;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            &:focus-within {
                border-bottom-color: #667eea;
                
                .van-field__label {
                    color: #667eea;
                }
            }
            
            .van-field__label {
                width: 80px;
                color: #333;
                font-weight: 600;
                font-size: 14px;
            }
            
            .van-field__control {
                font-size: 15px;
                color: #333;
                font-weight: 500;
                
                &::placeholder {
                    color: #999;
                    font-weight: 400;
                }
            }
            
            .van-field__error-message {
                font-size: 12px;
                margin-top: 4px;
            }
        }
    }
    
    .action-section {
        .register-btn {
            height: 52px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            font-size: 16px;
            font-weight: 600;
            color: white;
            margin-bottom: 20px;
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            
            &::before {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
                transition: left 0.5s;
            }
            
            &:hover::before {
                left: 100%;
            }
            
            &:active {
                transform: translateY(1px);
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            }
        }
        
        .login-link {
            text-align: center;
            color: #666;
            font-size: 14px;
            
            .link {
                color: #667eea;
                font-weight: 600;
                text-decoration: none;
                margin-left: 4px;
                transition: all 0.3s ease;
                
                &:hover {
                    color: #764ba2;
                    text-decoration: underline;
                }
            }
        }
    }
}

@keyframes float {
    0%, 100% {
        transform: translateY(0px) rotate(0deg);
    }
    50% {
        transform: translateY(-10px) rotate(180deg);
    }
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

// 响应式设计
@media (max-width: 480px) {
    .register-container {
        padding: 15px;
    }
    
    .register-card {
        .card-header {
            padding: 30px 20px 15px;
            
            .title {
                font-size: 24px;
            }
        }
    }
    
    .register-form {
        padding: 30px 20px;
        
        .avatar-section .avatar-upload .avatar-container {
            width: 100px;
            height: 100px;
        }
    }
}

@media (max-width: 360px) {
    .register-form {
        padding: 20px 15px;
    }
}
</style>